<template>
    <div class="zs-table-page-container">
        <div class="zs-card-sm zs-space-bottom zs-layout-flex-row zs-layout-justify-between">
            <span>
                <el-select v-model="projectZylyCode" filterable class="zs-select-md zs-space-right-sm" placeholder="项目名称"
                    @change="changeProject()">
                    <el-option v-for="item in projectList" :key="item.projectZylyCode" :label="item.projectName"
                        :value="item.projectZylyCode" />
                </el-select>
                <el-select v-model="brandName" filterable class="zs-select-md zs-space-right-sm" placeholder="品牌" @change="changeBrand()">
                    <el-option v-for="(item, index) in brandList" :key="index" :label="item.brandName"
                        :value="item.brandName" />
                </el-select>
                <el-select v-model="goodsName" class="zs-select-md zs-space-right-sm" placeholder="商品名称" filterable :no-data-text="'暂无数据，请选择品牌'">
                    <el-option v-for="(item, index) in goodsList" :key="index" :label="item.productName"
                        :value="item.productName" />
                </el-select>
                <el-popover popper-class="zs-popper" placement="bottom-end" trigger="click">
                    <template #reference>
                        <el-button class="zs-btn-square-solid"
                            :class="{ 'zs-btn-square-solid-active': startDateSelect || endDateSelect }">
                            <el-icon>
                                <MoreFilled />
                            </el-icon>
                        </el-button>
                    </template>
                    <template #default>
                        <div>
                            <el-date-picker class="zs-space-right-sm" v-model="startDateSelect" :type="pickerDate"
                                placeholder="开始日期" :clearable="false" :value-format="valueFormat" :teleported="false" @change="changeDate()"/>
                            <el-date-picker class="zs-space-right-sm" v-model="endDateSelect" :type="pickerDate"
                                placeholder="结束日期" :clearable="false" :value-format="valueFormat" :teleported="false" @change="changeDate()"/>
                        </div>
                    </template>
                </el-popover>
                <el-button class="zs-btn-plain" @click="getData()">
                    查询
                </el-button>
            </span>
            <span class="zs-layout-flex-row">
                <div class="db-btn zs-space-right-sm" :class="{ 'db-btn-primary': curTab == '日' }" @click="changeTab('日')">
                    按日
                </div>
                <div class="db-btn zs-space-right-sm" :class="{ 'db-btn-primary': curTab == '月' }" @click="changeTab('月')">
                    按月
                </div>
                <div class="db-btn zs-space-right" :class="{ 'db-btn-primary': curTab == '年' }" @click="changeTab('年')">按年
                </div>
                <el-button class="zs-btn-plain" @click="handleDownload" disabled><el-icon class="el-icon--left">
                        <Upload />
                    </el-icon>导出</el-button>
            </span>
        </div>
        <div class="zs-card zs-table-page-content" v-loading="loading">
            <el-table :data="tableData" class="zs-table-page-main" :stripe="stripe">
                <el-table-column label="序号" width="60" :align="'center'">
                    <template #default="scope">
                        {{ scope.$index + 1 + curPageSize * (currentPage - 1) }}
                    </template>
                </el-table-column>
                <el-table-column prop="timeDate" label="日期" width="120" :align="'center'"></el-table-column>

                <el-table-column label="进货成本" :align="'right'">
                    <template #default="scope">
                        {{ toThousands(scope.row.purchaseCost) }}
                    </template>
                </el-table-column>
                <el-table-column label="销货成本" :align="'right'">
                    <template #default="scope">
                        {{ toThousands(scope.row.salesCost) }}
                    </template>
                </el-table-column>
                <el-table-column label="存货成本" :align="'right'">
                    <template #default="scope">
                        {{ toThousands(scope.row.annualSales) }}
                    </template>
                </el-table-column>

                <el-table-column label="累计进货（月）" :align="'right'" v-if="curTab == '月'">
                    <template #default="scope">
                        {{ toThousands(scope.row.sumAnnualPurchase) }}
                    </template>
                </el-table-column>
                <el-table-column label="累计销货（月）" :align="'right'" v-if="curTab == '月'">
                    <template #default="scope">
                        {{ toThousands(scope.row.sumAnnualSales) }}
                    </template>
                </el-table-column>

                <el-table-column label="累计进货（年）" :align="'right'" v-if="curTab == '年'">
                    <template #default="scope">
                        {{ toThousands(scope.row.sumAnnualPurchase) }}
                    </template>
                </el-table-column>
                <el-table-column label="累计销货（年）" :align="'right'" v-if="curTab == '年'">
                    <template #default="scope">
                        {{ toThousands(scope.row.sumAnnualSales) }}
                    </template>
                </el-table-column>

                <!-- <el-table-column prop="" label="操作" width="100" :align="'right'">
                    <template #default="scope">
                        <el-button class="zs-link" link size="small" @click="goDetail(scope.row)">查看</el-button>
                    </template>
                </el-table-column> -->
            </el-table>

            <div class="zs-text-gray-dark zs-text-sm zs-space-top" v-if="curTab == '日'">*进货成本，销货成本，存货成本：元</div>
            <div class="zs-text-gray-dark zs-text-sm zs-space-top" v-if="curTab == '月'">
                *进货成本，销货成本，累计进货（月），累计销货（月）：元</div>
            <div class="zs-text-gray-dark zs-text-sm zs-space-top" v-if="curTab == '年'">
                *进货成本，销货成本，累计进货（年），累计销货（年）：元</div>
            <div class="zs-space-top-sm zs-table-page-pagination">
                <el-pagination v-model:currentPage="currentPage" v-model:page-size="curPageSize" :page-sizes="curPageSizes"
                    :small="true" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </div>
    </div>
</template>
<script setup>
import dbPublicApi from '@/api/dbPublic'
import detailApi from '@/api/SelfSupport/detailPages'
import { ElMessage } from 'element-plus'
import { dateFormat, toThousands } from '@/utils/number-util'
import { downloadNewFile } from "@/utils/publicUtils"
import { ref } from 'vue'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
let store = useStore()
const stripe = ref(true)
const route = useRoute().query

let loading = ref(true)


const curTime = route.dataTime
const updateDate = route.updateDate
const tabPermi = route.tabPermi
let curTab = ref(route.curTab)

let startDate = ref('')
let endDate = ref('')
let startDateSelect = ref('') // 筛选项 开始日期
let endDateSelect = ref('') // 筛选项 结束日期
let valueFormat = ref('YYYY-MM-DD')
let pickerDate = ref('date')

let projectZylyCode = ref(route.projectZylyCode)
let projectName = ref(route.projectName)
let projectList = ref([])

let brandName = ref(route.brandName)
let brandList = ref([]) // 品牌列表

let goodsName = ref(route.goodsName)
let goodsList = ref([])

const getPorjectList = async () => {
    await dbPublicApi.queryProjectPcApi({ dataTime: updateDate, resourceKey: tabPermi }).then((res) => {
        if (res.data.code == 200) {
            projectList.value = res.data.data
        }
    })
}
const changeProject = () => {
    const project = projectList.value.find(item => {
        return item.projectZylyCode == projectZylyCode.value
    })
    projectName.value = project.projectName
    brandName.value = ''
    goodsName.value = ''
    getBrandList()
    // getGoodsNameList()
    goodsList.value = []
}

const changeBrand = () => {
    goodsName.value = ''
    getGoodsNameList()
}

// 获取品牌列表
const getBrandList = async () => {
    await detailApi.queryControlBrandApi({ projectName: projectName.value }).then((res) => {
        if (res.data.code == 200) {
            brandList.value = res.data.data
        }
    })
}

// 获取商品名称列表
const getGoodsNameList = async () => {
    await detailApi.queryControlProductApi({ projectName: projectName.value, brandName: brandName.value }).then((res) => {
        if (res.data.code == 200) {
            goodsList.value = res.data.data
        }
    })
}

const handleDownload = async () => {
    const fileName = `品牌${curTab.value}列表.xls`
    let fileData
    await detailApi.brandExportApi({ projectZylyCode: projectZylyCode.value, ppcname: brandName.value, startDate: startDate.value, endDate: endDate.value, timeType: curTab.value }).then(res => {
        fileData = res.data
    })
    downloadNewFile(fileData, fileName)
}

const changeTab = (value) => {
    curTab.value = value
    if (curTab.value == '日') {
        startDate.value = dateFormat(new Date(new Date(updateDate).getTime() - 30 * 24 * 60 * 60 * 1000), 'YYYY-MM-DD')
        endDate.value = updateDate
        valueFormat.value = 'YYYY-MM-DD'
        pickerDate.value = 'date'
    }
    if (curTab.value == '月') {
        const year = new Date(updateDate).getFullYear() - 2
        const data = dateFormat(new Date(updateDate), 'YYYY-MM')
        startDate.value = data.replace(data.substring(0, 4), year)
        endDate.value = dateFormat(new Date(updateDate), 'YYYY-MM')
        valueFormat.value = 'YYYY-MM'
        pickerDate.value = 'month'
    }
    if (curTab.value == '年') {
        const year = new Date(updateDate).getFullYear() - 20
        startDate.value = year.toString()
        endDate.value = new Date(updateDate).getFullYear().toString()
        valueFormat.value = 'YYYY'
        pickerDate.value = 'year'
    }
    if (isSelect.value) {
        startDateSelect.value = isSelect.value ? startDate.value : ''
        endDateSelect.value = isSelect.value ? endDate.value : ''
    }
    // getPorjectList()
    // getBrandList()
    // getGoodsNameList()
    getData()
}

// 分页
const curPageSizes = ref(store.state.uiPageSizes)
let curPageSize = ref(store.state.uiPageSizeDefault)
let currentPage = ref(1)
const total = ref(0)
const handleSizeChange = (val) => {
    curPageSize.value = val
    getList()
}
const handleCurrentChange = (val) => {
    currentPage.value = val
    getList()
}

const tableData = ref([])
// 未选择日期组件时，使用url参数查询，选择了日期之后，使用页面选择的日期（ps: 为了默认进来显示出【开始日期】【结束日期】）
const isSelect = ref(false)
const changeDate = () => {
    isSelect.value = true
}
const getList = () => {
    if (isSelect.value && ((startDateSelect.value && !endDateSelect.value) || (!startDateSelect.value && endDateSelect.value))) {
        ElMessage({
            message: '请选择开始日期和结束日期',
            type: 'warning',
        })
        return false
    }
    let start = isSelect.value ? startDateSelect.value : startDate.value
    let end = isSelect.value ? endDateSelect.value : endDate.value
    loading.value = true
    detailApi.queryProductApi({ projectName: projectName.value, startDate: start, endDate: end, brandName: brandName.value, productName: goodsName.value, timeType: curTab.value, pageNo: currentPage.value, pageSize: curPageSize.value }).then((res) => {
        if (res.data.code == 200) {
            tableData.value = res.data.data.data
            total.value = res.data.data.totalCount
            loading.value = false
        }
    })
}
const getData = () => {
    currentPage.value = 1
    tableData.value = []
    total.value = 0
    getList()
}

// const goDetail = (row) => {
//     router.push({
//         path: '/page/routeController/index',
//         query: {
//             rid: 'SelfSupport/detailPages/inventoryManagement/goodsList',
//             rTitle: '品牌商品',
//             updateDate: updateDate, // 数据更新日期
//             tabPermi: tabPermi, // 权限标识
//             brandName: brandName.value, // 品牌名称
//             projectZylyCode: projectZylyCode.value,
//             projectName: projectName.value,
//             dataTime: row.timeDate,
//             curTab: curTab.value, // 日月年
//         },
//     })
// }

const init = () => {
    if (curTab.value == '日') {
        startDate.value = dateFormat(new Date(new Date(curTime).getTime() - 30 * 24 * 60 * 60 * 1000), 'YYYY-MM-DD')
        endDate.value = curTime
        valueFormat.value = 'YYYY-MM-DD'
        pickerDate.value = 'date'
    }
    if (curTab.value == '月') {
        const year = new Date(curTime).getFullYear() - 2
        const data = dateFormat(new Date(curTime), 'YYYY-MM')
        startDate.value = data.replace(data.substring(0, 4), year)
        endDate.value = dateFormat(new Date(curTime), 'YYYY-MM')
        valueFormat.value = 'YYYY-MM'
        pickerDate.value = 'month'
    }
    if (curTab.value == '年') {
        const year = new Date(curTime).getFullYear() - 20
        startDate.value = year.toString()
        endDate.value = new Date(curTime).getFullYear().toString()
        valueFormat.value = 'YYYY'
        pickerDate.value = 'year'
    }
    getPorjectList()
    getBrandList()
    getGoodsNameList()
    getData()
}
init()
</script>
  
  
<style scoped lang="scss"></style>